﻿using Ops.Host.Core.Models;

namespace Ops.Host.Core.Services.Impl;

internal sealed class DictInfoService : IDictInfoService
{
    private readonly IFreeSql _freeSql;

    public DictInfoService(IFreeSql freeSql) => _freeSql = freeSql;

    public (List<DictInfo> items, long count) GetPaged(DictInfoFilter filter, int pageIndex, int pageItems)
    {
        var items = _freeSql.Select<DictInfo>()
                            .WhereIf(!string.IsNullOrEmpty(filter.Category), s => s.Category == filter.Category)
                            .Count(out var total)
                            .Page(pageIndex, pageItems)
                            .ToList();
        return (items, total);
    }

    public async Task<DictInfo> AddDictInfoAsync(DictInfo model)
    {
        var repo = _freeSql.GetRepository<DictInfo>();
        return await repo.InsertAsync(model);
    }

    public async Task UpdateDictInfoAsync(DictInfo model)
    {
        var repo = _freeSql.GetRepository<DictInfo>();
        var dictInfo = repo.Where(s => s.Id == model.Id).First();

        if (dictInfo != null)
        {
            dictInfo.Name = model.Name;
            dictInfo.Alias = model.Alias;
            dictInfo.Code = model.Code;

            await repo.UpdateAsync(dictInfo);
        }
    }

    public void DeleteDictInfo(int id)
    {
        _freeSql.Delete<DictInfo>(id).ExecuteAffrows();
    }
}
